import React, { Component } from "react";
import { Layout, Menu, Modal } from "antd";
import { withRouter } from "react-router-dom";
const { Header } = Layout;

class NavHeader extends Component {
  state = {
    username: "",
    flag: false,
    visible: false,
  };
  componentDidMount() {
    this.checkUserInfo();
  }
  checkUserInfo = () => {
    const userInfo = JSON.parse(localStorage.getItem("userInfo")) || {};
    console.log(userInfo);
    if (userInfo.username) {
      this.setState({ username: userInfo.username, flag: true });
    }
  };
  handleOk = (e) => {
    //清除本地存储
    //跳转到登录页面
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
    this.props.history.replace("/login");
  };

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  };
  clickMenuItem = ({ key }) => {
    switch (key) {
      case "exit":
        //弹窗提示
        this.setState({ visible: true });
    }
  };
  render() {
    const { username, flag } = this.state;
    return (
      <div>
        <Header className="header" style={{ display: "flex" }}>
          <div className="logo">
            <>{flag && <h1 style={{ color: "#eee" }}>欢迎 {username} </h1>}</>
          </div>
          <Menu theme="dark" mode="horizontal" onClick={this.clickMenuItem}>
            <Menu.Item key="exit">退出登录</Menu.Item>
          </Menu>
          <Modal
            title="提示"
            visible={this.state.visible}
            onOk={this.handleOk}
            onCancel={this.handleCancel}
            okText="确定"
            cancelText="取消"
          >
            你确定要退出登录吗？
          </Modal>
        </Header>
      </div>
    );
  }
}
export default withRouter(NavHeader);
